﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using Transcend.FileUploader.Dao;
using System.IO;
using System.Xml;
using Transcend.FileUploader.Utility;
using Spring.Context.Support;
using Spring.Context;
using Transcend.FileUploader.Entity;
using System.Collections;
using System.Threading;
using System.Data.Common;
using Transcend.Utility;
using System.Xml.Linq;
using System.Linq;
using System.Text.RegularExpressions;
using System.Data.OleDb;

namespace Transcend.FileUploader
{
    public partial class MainWindow : Form
    {

        #region 属性

        private static IApplicationContext springContext;

        private static DictionaryWraper appSetting;

        private UploadSetting uploadSetting = null;

        private LoginUser loginUser = null;

        private bool StopUpload = false;

        /// <summary>
        /// 登录用户ID，用于外部传参
        /// </summary>
        public string UserId { get; set; }

        public static readonly System.Text.RegularExpressions.Regex PlaceHolderRegex = new System.Text.RegularExpressions.Regex("~[^~]+~");

        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #endregion

        public MainWindow()
        {

            try
            {
                springContext = ContextRegistry.GetContext();
                appSetting = springContext.GetObject("app.settings") as DictionaryWraper;

                InitializeComponent();

                string compName = appSetting.GetString("app.company_name");
                string appName = appSetting.GetString("app.product_name");
                this.Text = string.Format("{0} - {1}", appName, compName);
            }
            catch (Exception ex)
            {
                logger.Error("读取spring配置文件出错", ex);
                MessageBox.Show("读取spring配置出错，错误详细请查看日志");
                Application.Exit();
            }
        }

        #region UI事件处理

        private void MainWindow_Load(object sender, EventArgs e)
        {

            try
            {
                uploadSetting = GetUploadSetting();
            }
            catch (Exception ex)
            {
                logger.Error("配置信息被破坏", ex);
            }

            if (uploadSetting == null)
            {
                if (MessageBox.Show(this, "没有发现配置信息或配置信息被破坏，是否重新配置", "读取配置错误", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    ShowUserConfigWindow();
                }
                else
                {
                    Application.Exit();
                }
            }

            if (uploadSetting == null)
            {
                Application.Exit();
            }


            if (loginUser == null)
            {
                ShowUserLoginWindow();
            }
        }

        private void Bn_AddFile_Click(object sender, EventArgs e)
        {
            if (tabContainer.SelectedTab == tabImage)
            {
                AddImageFolder();
            }
        }
        /// <summary>
        /// 添加图形文件夹
        /// </summary>
        private void AddImageFolder()
        {
            string selectedPath = null;
            if (DialogResult.OK == folderBrowserDialog1.ShowDialog(this))
            {
                selectedPath = folderBrowserDialog1.SelectedPath;
                for (int i = 0; i < Lb_SelectedFile.Items.Count; i++)
                {
                    if (Lb_SelectedFile.Items[i].ToString() == selectedPath)
                    {
                        MessageBox.Show("重复添加相同路径", "错误", MessageBoxButtons.OK);
                        return;
                    }
                }
                Lb_SelectedFile.Items.Add(selectedPath);
            }
        }



        private void Bn_ClearFile_Click(object sender, EventArgs e)
        {
            Lb_SelectedFile.Items.Clear();
        }

        private void Bn_DeleteFile_Click(object sender, EventArgs e)
        {
            if (tabContainer.SelectedTab == tabImage)
            {
                RemoveImageDir();
            }
        }
        //移除选中的图像目录
        private void RemoveImageDir()
        {
            if (Lb_SelectedFile.SelectedIndex == -1)
            {
                return;
            }

            Lb_SelectedFile.Items.RemoveAt(Lb_SelectedFile.SelectedIndex);
        }


        private void Bn_UploadFile_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(loginUser.UserId))
            {
                MessageBox.Show("请先登录，然后再上传。");
                return;
            }

            UploadImage();
            return;
        }




        /// <summary>
        /// 上传图像
        /// </summary>
        private void UploadImage()
        {
            UploadSetting uploadSetting = null;

            try
            {
                uploadSetting = GetUploadSetting();
            }
            catch (Exception ex)
            {
                logger.Error("配置文件损坏", ex);
                if (MessageBox.Show("配置文件损坏，是否重新配置？") != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                ShowUserConfigWindow();
                uploadSetting = GetUploadSetting();
            }

            uploadSetting.IsIncrementUpload = false;
            StartUpload(uploadSetting);
        }

        private void Bn_IncrUpload_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show(this, "增量上传会将电子档案添加到现有电子档案中，是否继续？", "增量上传警告", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            UploadSetting uploadSetting = null;
            try
            {
                uploadSetting = GetUploadSetting();
            }
            catch (Exception ex)
            {

                logger.Error("配置文件损坏", ex);
                if (MessageBox.Show("配置文件损坏，是否重新配置？") != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                ShowUserConfigWindow();
                uploadSetting = GetUploadSetting();
            }

            // 增量上传
            uploadSetting.IsIncrementUpload = true;
            StartUpload(uploadSetting);

        }

        private void Bn_CancelUpload_Click(object sender, EventArgs e)
        {

        }

        private void MI_UserLogin_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = sender as ToolStripMenuItem;
            if (mi.Text == "登录")
            {
                ShowUserLoginWindow();
            }
            else
            {
                if (MessageBox.Show(this, "确定要登出吗？", "确认", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK) return;
                mi.Text = "登录";
                Bn_UploadFile.Enabled = false;
                Bn_IncrUpload.Enabled = false;
                Bn_AbortUpload.Enabled = false;
                loginUser = null;
            }
        }

        private void MI_UploadSetting_Click(object sender, EventArgs e)
        {
            ShowUserConfigWindow();
        }


        private void tsStop_ButtonClick(object sender, EventArgs e)
        {

        }

        private void StartUpload(UploadSetting uploadSetting)
        {

            TS_UploadStatus.Text = "";

            var topDirs = new string[Lb_SelectedFile.Items.Count];
            Lb_SelectedFile.Items.CopyTo(topDirs, 0);

            StringCollection dirs = LoadDirectories(topDirs);

            if (dirs.Count == 0)
            {
                MessageBox.Show("请添加要上传的数据");
                return;
            }

            // logger.Info("开始上传");

            DocInstance doc = null;
            int total = dirs.Count;
            int failed = 0;
            int success = 0;
            int finished = 0;
            upProgress.Maximum = dirs.Count;
            upProgress.Minimum = 0;
            upProgress.Value = 0;
            tsStop.Visible = true;
            StopUpload = false;
            Application.DoEvents();
            foreach (string dir in dirs)
            {
                if (Directory.Exists(dir))
                {
                    try
                    {
                        logger.Info(string.Format("上传:{0}", dir));
                        doc = CreateDocInstanceFromDirectory(dir, uploadSetting, springContext);
                        Application.DoEvents();
                        SaveDocInstance(ref doc, ref uploadSetting);
                        ++success;
                    }
                    catch (Exception ex)
                    {
                        ++failed;
                        logger.Error("错误:", ex);
                        if (!uploadSetting.IgnoreError)
                        {
                            MessageBox.Show(string.Format("上传{0}发生错误：{1}", dir, ex.Message), "错误");
                        }
                    }
                    finally
                    {
                        ++finished;
                        TS_UploadStatus.Text = string.Format("已完成{0}/{1}，成功:{2}，错误:{3}", (success + failed), total, success, failed);
                    }
                }
                else
                {
                    logger.Warn(string.Format("目录被移动：{0}，已被忽略", dir));
                }
                upProgress.Value++;
                Application.DoEvents();
                if (StopUpload) break;
            }

            string finishMessage = string.Format("{3}。 共计：{0} 成功: {1} 错误:{2}", total, success, failed, StopUpload ? "上传中断" : "上传完成");
            StopUpload = false;
            tsStop.Visible = false;
            logger.Info(finishMessage);
            MessageBox.Show(finishMessage);

        }

        #endregion

        #region 上传相关

        /// <summary>
        /// 单例存储
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="uploadSetting"></param>
        private void SaveDocInstance(ref DocInstance doc, ref UploadSetting uploadSetting)
        {

            using (var db = new Transcend.DP3.Db.Database(uploadSetting.StorageConnectionString))
            {

                StoreDocument dao = new StoreDocument(db);
                dao.EncryptedImage = uploadSetting.EncryptedImage;
                if (uploadSetting.EncryptedImage)
                {
                    //图像已加密
                    dao.ImagePassword = uploadSetting.ImagePassword;
                }
                dao.AppType = uploadSetting.AppType;
                var oldDoc = dao.GetInstance(doc.Pk, doc.AppTypeId);

                try
                {
                    db.BeginTrans();
                    // 增量上传
                    if (uploadSetting.IsIncrementUpload)
                    {
                        if (oldDoc == null)
                        {
                            throw new InvalidOperationException("增量上传失败，没有找到匹配的电子档案");
                        }

                        MergeDocument(oldDoc, doc);
                        dao.SaveInstance(oldDoc);
                    }
                    else
                    {
                        if (oldDoc != null)
                        {
                            if (uploadSetting.OverrideWarm)
                            {
                                if (!uploadSetting.OverrideSetting.NoConfirmAnyMore)
                                {
                                    OverrideOptionsDialog confirmWin = new OverrideOptionsDialog("覆盖提示", string.Format("电子档案[{0}]已经存在，是否覆盖？", doc.LocalDir));
                                    confirmWin.ShowDialog();
                                    uploadSetting.OverrideSetting = confirmWin.WindowResult;
                                }

                                if (!uploadSetting.OverrideSetting.ShouldOverride)
                                {
                                    logger.Info("电子档案已经存在，用户取消覆盖");
                                    return;
                                }
                            }

                            switch (uploadSetting.OverrideAction)
                            {
                                case OverrideAction.DeleteDocPage:
                                    doc.Id = oldDoc.Id;
                                    dao.DeleteAllDocPage(oldDoc.Id);
                                    break;
                                case OverrideAction.MarkDocPage:
                                    throw new NotSupportedException(string.Format("该覆盖{0}方式不受支持", Enum.GetName(typeof(OverrideAction), OverrideAction.MarkDocPage)));
                            }
                        }
                        dao.SaveInstance(doc);
                    }

                    // 写日志
                    using (var infoConn = new Transcend.DP3.Db.Database(uploadSetting.DocInfoConnectionString))
                    {
                        WriteLog(infoConn, ref doc);
                    }

                    dao.UploadImage();
                    //更新目录
                    //var proc = appSetting.GetString("uploader.insert_certName");
                    //if (string.IsNullOrEmpty(proc))
                    //    throw new ArgumentException("生成图像目录的存储过程没有配置uploader.insert_certName");
                    //using (var cmd = db.mkCommand(proc, CommandType.StoredProcedure))
                    //{
                    //    var p = Transcend.DP3.Db.Database.mkParam(cmd, "p_pk", doc.Pk);
                    //    p.Direction = ParameterDirection.Input;
                    //    cmd.ExecuteNonQuery();
                    //}
                    db.Commit();
                }
                catch (Exception ex)
                {
                    db.Rollback();
                    logger.Error("上传错误：", ex);
                    throw ex;
                }
            }
        }

        int matchCount = 0;
        private void ReadDocInfo(string path, ref DocInstance doc, ref UploadSetting uploadSetting)
        {

            var dataContext = new Dictionary<string, object> {
				{"UPLOAD_YYYY", DateTime.Now.Year.ToString("D4")},
				{"UPLOAD_MM", DateTime.Now.Month.ToString("D2")},
				{"UPLOAD_DD", DateTime.Now.Day.ToString("D2")},
				{"UPLOAD_HH", DateTime.Now.Hour.ToString("D2")},
				{"UPLOAD_MI", DateTime.Now.Minute.ToString("D2")},
				{"UPLOAD_GUID", Guid.NewGuid().ToString()}
			};

            string docSql = null;
            string CASENO = Path.GetFileName(path);



            if (uploadSetting.ParseDocId && !uploadSetting.ParseDocNo)
            {
                docSql = appSetting.GetString("uploader.docinfo_by_docno");
                docSql = docSql.Replace(":docno", CASENO);
            }
            matchCount = 0;
            using (var db = new Transcend.DP3.Db.Database(uploadSetting.DocInfoConnectionString))
            {
                using (var cmd = db.mkCommand(docSql))
                {
                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            doc.DocNo = ConvertHelper.ToStr(dr["docno"], string.Empty);
                            doc.DocId = ConvertHelper.ToStr(dr["docid"], string.Empty);
                            doc.Pk = ConvertHelper.ToStr(dr["pk"], string.Empty);

                            Transcend.DP3.Helper.CollectionHelper.Merge(dataContext, true, Transcend.DP3.Db.Database.RowToDic(dr));
                            doc.Uri = BuildStoreURI(appSetting.GetString("uploader.store_path_template"), dataContext);
                            if (++matchCount > 1) throw new ArgumentException(string.Format("原文挂接出现异常，在档案中找到1个以上匹配的档案信息，路径：{0}，SQL：{1}", path, docSql));
                        }
                    }
                }
                //获取设置的分区号
                string PartitionSetSQL = appSetting.GetString("uploader.default_Partition_ID");
                if (!string.IsNullOrWhiteSpace(PartitionSetSQL))
                {
                    doc.isPartition = true;
                    using (var cmd = db.mkCommand(PartitionSetSQL))
                    {
                        var re = cmd.ExecuteScalar();
                        if (re != null)
                        {
                            doc.DIVISION_ID = int.Parse(re.ToString());
                        }
                    }
                }
                else
                {
                    doc.isPartition = false;
                }
            }
            if (matchCount == 0) throw new InvalidOperationException(string.Format("没有找到匹配的档案信息{0}", docSql));
        }

        /// <summary>
        /// 取得存储路径、文件夹路径、FTP路径
        /// </summary>
        private static string BuildStoreURI(string format, Dictionary<string, object> data)
        {
            var ret = string.Empty;

            var mc = PlaceHolderRegex.Matches(format);
            var holder = string.Empty;
            object holderVal = null;
            var strIndex = 0;

            foreach (System.Text.RegularExpressions.Match m in mc)
            {

                holder = m.Value.Substring(1, m.Value.Length - 2).ToUpper();
                if (!data.ContainsKey(holder))
                {
                    throw new ArgumentException(string.Format("没有找到存储路径中占位符{0}对应的数据项", holder));
                }

                holderVal = data[holder];
                if (holderVal == null) holderVal = "_";

                ret += format.Substring(strIndex, m.Index - strIndex);
                ret += holderVal;

                strIndex = m.Index + m.Value.Length;
            }

            return ret;
        }

        private void MergeDocument(DocInstance dstDoc, DocInstance srcDoc)
        {
            DocCategory nc = null;
            DocPage np = null;
            foreach (DocCategory oc in srcDoc.Category)
            {

                nc = new DocCategory();
                //nc.BusinessId = oc.BusinessId;
                nc.Copies = oc.Copies;
                //nc.CreateTime = oc.CreateTime;
                //nc.CredId = oc.CredId;
                //nc.CredType = oc.CredType;
                nc.Name = oc.Name;
                nc.IsDouble = oc.IsDouble;
                nc.Keyword = oc.Keyword;
                nc.Notes = oc.Notes;
                nc.PageNum = oc.PageNum;
                //nc.ParentItemId = oc.ParentItemId;
                nc.RowNo = oc.RowNo;
                nc.ScanNum = oc.ScanNum;
                dstDoc.Add(nc);
                foreach (DocPage op in oc.DocPage)
                {
                    np = new DocPage();
                    np.Data = op.Data;
                    np.Extension = op.Extension;
                    np.Keyword = op.Keyword;
                    np.LocalPath = op.LocalPath;
                    np.PageNo = op.PageNo;
                    np.PageNum = op.PageNum;
                    np.RawFileName = op.RawFileName;
                    np.Size = op.Size;
                    np.Status = op.Status;
                    np.UserId = op.UserId;
                    nc.Add(np);
                }
            }
        }

        private void ShowUserConfigWindow()
        {
            UserConfigWindow win = new UserConfigWindow(this.uploadSetting);
            if (win.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.uploadSetting = win.UploadSetting;
            }
        }

        private void ShowUserLoginWindow()
        {
            string connectionString = connectionString = uploadSetting.DocInfoConnectionString;
            UserLoginWindow win = new UserLoginWindow(connectionString, appSetting.GetString("uploader.user_login_sql"));
            if (win.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                loginUser = win.User;
                Bn_UploadFile.Enabled = true;
                Bn_IncrUpload.Enabled = true;
            }
            if (loginUser != null)
            {
                MI_UserLogin.Text = string.Format("登出：{0}({1})", loginUser.Name, loginUser.LoginName);
            }
            else
            {
                MI_UserLogin.Text = "登录";
            }
        }

        private static StringCollection LoadDirectories(string[] dirs)
        {

            var allDirs = new StringCollection();
            string path = null;

            for (int i = 0; i < dirs.Length; i++)
            {
                path = dirs[i].ToString();
                ResuriveDir(path, ref allDirs);
            }

            return allDirs;
        }

        /// <summary>
        /// 写上传日志
        /// </summary>
        private void WriteLog(Transcend.DP3.Db.Database db, ref DocInstance doc)
        {
           // INSERT INTO CS_SCAN.DS_SCAN_LOG(PAGE_ID,ITEM_ID,ID,INST_ID,CREATE_USER_ID,CREATE_DATE,DIVISION_ID) 
           // VALUES (:PAGE_ID,:ITEM_ID,':ID',:INST_ID,:CREATE_USER_ID,sysdate,:DIVISION_ID)
            var cmdText = appSetting.GetString("uploader.log_sql");

            foreach (var c in doc.Category)
            {
       
                cmdText = cmdText.Replace(":INST_ID", c.InstId.ToString());
                cmdText = cmdText.Replace(":CREATE_USER_ID", "'"+loginUser.LoginName+"'");
                if (!doc.isPartition)
                {
                    cmdText = cmdText.Replace(",:DIVISION_ID", "").Replace(",DIVISION_ID", "");
                }
                else
                {
                    cmdText = cmdText.Replace(":DIVISION_ID", doc.DIVISION_ID.ToString());
                }
                foreach (var p in c.DocPage)
                {
                    var id_sql = "SELECT cs_Scan.SEQ_DS_SCAN_LOG.nextval from dual";
                    var id = 0M;
                    db.QueryField<decimal>(ref id, id_sql);

                    cmdText = cmdText.Replace(":ID", "'" + id.ToString() + "'");
                    cmdText = cmdText.Replace(":ITEM_ID", p.ItemId.ToString());
                    cmdText = cmdText.Replace(":PAGE_ID", p.Id.ToString());
                    db.Execute(cmdText);
                }
            }
        }

        /// <summary>
        /// 获取所有最下级目录
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dirs"></param>
        private static void ResuriveDir(string path, ref StringCollection dirs)
        {
            string[] subDir = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
            if (subDir == null || subDir.Length == 0)
            {
                dirs.Add(path);
                return;
            }

            foreach (string d in subDir)
            {
                ResuriveDir(d, ref dirs);
            }
        }

        private UploadSetting GetUploadSetting()
        {
            uploadSetting = UserConfigWindow.ReadUserConfig();
            uploadSetting.OverrideSetting = new OverrideSetting();
            uploadSetting.AppType = new DocStorageAppType();
            uploadSetting.DocInfoConnectionString = appSetting.GetString("uploader.docinfoconnectionstring");
            uploadSetting.StorageConnectionString = appSetting.GetString("uploader.storageconnectionstring");
            uploadSetting.AppType.Id = appSetting.GetDecimal("uploader.apptypeid", -1);
            if (string.IsNullOrEmpty(uploadSetting.DocInfoConnectionString))
            {
                throw new ArgumentException("数据库连接字符串[uploader.docinfoconnectionstring]没有配置");
            }
            if (string.IsNullOrEmpty(uploadSetting.StorageConnectionString))
            {
                throw new ArgumentException("数据库存储连接字符串[uploader.storageconnectionstring]没有配置");
            }
            if (uploadSetting.AppType.Id == -1)
            {
                throw new ArgumentException("存储应用分类[uploader.apptypeid]没有配置");
            }

            var overrideAction = appSetting.GetString("uploader.override_action");
            if (!string.IsNullOrEmpty(overrideAction))
            {
                uploadSetting.OverrideAction = (OverrideAction)Enum.Parse(typeof(OverrideAction), overrideAction);
            }

            return uploadSetting;
        }

        private static void GenerateDsItemUseCatalog(Transcend.DP3.Db.Database db, DocInstance doc)
        {
            var proc = appSetting.GetString("uploader.proc_dsitemfromfilecatalog");
            if (string.IsNullOrEmpty(proc))
                throw new ArgumentException("生成图像分类的存储过程没有配置uploader.proc_dsitemfromfilecatalog");
            using (var cmd = db.mkCommand(proc, CommandType.StoredProcedure))
            {
                var p = Transcend.DP3.Db.Database.mkParam(cmd, "pk", doc.Pk);
                p.Direction = ParameterDirection.Input;
                cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 从目录创建docinstance实例
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="uploadSetting"></param>
        private DocInstance CreateDocInstanceFromDirectory(string dir, UploadSetting uploadSetting, IApplicationContext sprintContext)
        {
            var parser = springContext.GetObject("uploader.filenameresolver") as SimpleStringLayout;
            if (!Directory.Exists(dir)) return null;

            string fileFilter = appSetting.GetString("uploader.doc_filter");
            DocInstance doc = null;
            DocCategory cate = null;
            DocPage page = null;
            doc = new DocInstance();
            doc.LastOperater = string.Format("{0}({1}-{2})", loginUser.UserId, loginUser.LoginName, loginUser.Name);
            doc.AppTypeId = (int)uploadSetting.AppType.Id;
            doc.LocalDir = dir;
            ReadDocInfo(dir, ref doc, ref uploadSetting);
            var files = Directory.GetFiles(dir);
            foreach (var f in files)
            {
                if (File.Exists(f))
                {
                    // 设置了文件后缀过滤
                    if (!string.IsNullOrEmpty(fileFilter))
                    {
                        if (fileFilter.IndexOf(Path.GetExtension(f.ToLower())) == -1)
                        {
                            continue;
                        }
                    }
                    cate = new DocCategory();
                    var fileclassifer = GetChinese(Path.GetFileNameWithoutExtension(f));
                    cate.Name = string.IsNullOrWhiteSpace(fileclassifer) ? appSetting.GetString("uploader.default_category_name") : fileclassifer;
                    page = new DocPage();
                    page.RawFileName = Path.GetFileName(f);
                    page.Extension = Path.GetExtension(f);
                    page.PageNo = ConvertHelper.ToInt32(parser.resolve(Path.GetFileNameWithoutExtension(f), "pageno"), 0);
                    page.LocalPath = f;
                    cate.Add(page);
                    doc.Add(cate);
                }
            }

            if (doc.Pages == 0)
            {
                throw new InvalidOperationException("{0}中无文档文件");
            }
            return doc;
        }

        #endregion


        /// <summary>  
        /// 用正则截取字符串中的中文  
        /// </summary>  
        /// <param name="strSource">源字符串</param>  
        /// <returns></returns>  
        private string GetChinese(string strSource)
        {

            Regex regex = new Regex(appSetting.GetString("uploader.ChineseRegex"));
            int nLength = strSource.Length;
            string chineseString = string.Empty;
            for (int i = 0; i < strSource.Length; i++)
            {
                if (regex.IsMatch(strSource.Substring(i, 1)))
                    chineseString = chineseString + strSource.Substring(i, 1);
            }
            return chineseString;
        }
    }
}